<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">


							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="出入库类型:" required>
											<u--input v-model="baseFormData.FType" placeholder="出入库类型" readonly
												border="none"></u--input>

										</u-form-item>
									</u-col>
									<u-col span="4">

										<u-form-item labelWidth="auto" label="出入库时间:">
											<u--input v-model="baseFormData.BillDate" placeholder="自动带出时间" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">

										<u-form-item labelWidth="auto" label="操作人员:" @click="openBaseScreen('人员')"
											required>
											<u--input v-model="baseFormData.StockMan" placeholder="请选择操作人员" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>

								</u-row>

							</u--form>



						</view>
						<view class="AddBottomBox">

							<view class="CancelBtn CancelBtnIcon">
								<u-icon class="icon" name="scan" color="#51d0d0" size="30" @click="ScanClick"></u-icon>
							</view>
							<button class="CancelBtn" @click="Addsubtable()">新增</button>
						</view>
						<view class="table">
							<table>
								<tr>
									<th width="10%">操作</th>
									<th>库位</th>
									<th>模具</th>
								</tr>

								<tr v-for="(item, index) in tableData">
									<td>
										<uni-icons type="trash" size="30" @click="trash(index)"></uni-icons>
									</td>
									<td @click='openBaseScreen("库位",index)'>
										<u--textarea v-model="item.FStorageName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>

									<td @click='openBaseScreen("模具",index)'>
										<u--textarea v-model="item.MoludName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
								</tr>

							</table>

						</view>
					</view>
					<view class="DetailsbottomBtns" v-show="ButtonShow">
						<button block @click="submit"  class="button1">
							{{submitButton}}
						</button>
					</view>


				</view>
			</template>

		</st-mc-framework>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm' :showCancelButton="true"
			@cancel='modalcancel'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>

		<!-- 	<u-picker :show="PickerShow" :columns="PickerColumns" keyName="label" @cancel='closeClick'
			@confirm='confirmClick'></u-picker> -->

		<uni-popup ref="popup_workshop" :is-mask-click="false">
			<view class="popup-container" :style="{ paddingTop:$u.addUnit(0 + $u.sys().statusBarHeight,'px') }">
				<!-- 车间选择区域 -->
				<scroll-view class="workshop-container" scroll-y>
					<view class="workshop-grid">
						<view v-for="(item, index) in PickerColumns" :key="index" class="workshop-item"
							@click="confirmClick(item)">
							<view class="workshop-info">
								<uni-icons class="uni_icons" color="#fff" fontFamily="CustomFont"
									:size="30">{{ $utils.toUniCode(item.PIC_PH) }}</uni-icons>
								<view class="workshop-name">
									{{ item.label }}
								</view>
							</view>

							<!-- <view class="workshop-remark">{{ item.FRemarks }}</view> -->
						</view>
					</view>
				</scroll-view>
				<view class="popup-bottom" :style="$utils.disposeSafeBottomFun()">
					<view class="close-button">
						<uni-icons type="close" size="56" color="#FFF" @click="closeClick()"></uni-icons>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {

				ButtonShow: true,
				baseFormData: {
					EquipmentID: null,
					EquipmentName: '',
					StockID: 0,
					BillDate: '', //时间
					EmplID: null, //人员id
					StockMan: '', //人员
					FStorageName: '', //库位
					FType: '', //领用还是归还
					FTypeID: '', //领用还是归还
				},

				tableData: [], //子表
				tableDataIndex: null, //子表索引
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				submitButton: '提交',
				
				FWorkshopID: null, //模块id
				PickerShow: false,
				PickerColumns: [{
					label: '归还',
					id: 'LY',
					PIC_PH: '&#xe60c;'
				}, {
					label: '领用',
					id: 'GH',
					PIC_PH: '&#xe60b;'
				}], //领用还是归还
				modalshow: false, //提示显示
				modaltitle: '提示', //提示提示
				modalcontent: '', //提示内容
				ModuleTitle: '', //标题名称
				showMLoading: false, //是否加载
				loadingName: '正在加载中……', //加载名称
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
		
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName;
			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
			that.Addsubtable()

		},
		onLoad(item) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});


			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;

			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (item.StockID) {
				setLoading(true);
				this.queryList(item.StockID);
				return;
			}

			// 统一处理表单默认值
			const formDefaults = {
				BillDate: getFormatDate(new Date()),
				StockMan: UserInfo.EmplName,
				EmplID: UserInfo.EmplID,
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
			};
			this.assignFormData(this.baseFormData, formDefaults);
			setLoading(false);

			this.$nextTick(() => {
				this.$refs.popup_workshop.open();
			});
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},

		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				console.log(res.data);
				this.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {
			ScanClick() {
				var that = this
				this.$scanPopup.openScan({
					success: function(res) {
						that.MoludChange(res.result, 'phone')
					},
					fail: function(fail) {
						console.log(fail);
					}
				})
			},
			gettableDatachild() {
				var tableDatachild = this.tableData[this.tableData.length - 1]
				return tableDatachild
			},
			// 处理扫码数据
			MoludChange(res, name) {
				let that = this;
				console.log(res);

				let parts = res.split("|");
				var id = parts[1]
				var tableDatachild = this.gettableDatachild()
				if (parts[0] == 'MJ') {
					if (tableDatachild.MoludName) {
						that.Addsubtable()
					}
					that.ADDMoludName(id)
				} else if (parts[0] == 'MS') {
					if (tableDatachild.FStorageName) {
						that.Addsubtable()
					}
					that.AddFStorageName(id)
				}
			},
			AddFStorageName(id, Defaults) { // 扫码获取库位数据
				let that = this;
				var formDefaults = Defaults ? Defaults : {}
				var tableDatachild = this.gettableDatachild()
				var obj = {
					FType: that.baseFormData.FTypeID == 'LY' ? 'GH' : 'LY',
					MoludID: 0,
					FStorageID: id,
					FStorageName: '',
					PageIndex: 1,
					PageSize: 30
				}
				that.Request.request('MJ_StorageList', obj, (res) => {
					console.log(res);
					const sourceData = res.data.ds.length > 0 ? res.data.ds : res.data.ds1;
					const {
						FStorageName = '', FStorageID = ''
					} = sourceData[0] || {};

					formDefaults = {
						...formDefaults,
						FStorageName,
						FStorageID
					};
					that.assignFormData(tableDatachild, formDefaults);
				})

			},
			ADDMoludName(id) { // 扫码获取模具数据
				let that = this;
				var formDefaults
				var tableDatachild = this.gettableDatachild()
				that.Request.request('getMoldDetail', {
					MoludID: id
				}, (ret) => {
					console.log(ret);
					formDefaults = {
						MoludName: ret.data.ds[0].MoludName,
						MoludID: ret.data.ds[0].MoludID
					};
					that.AddFStorageName(id, formDefaults)
				})

			},
			// 子表删除
			trash(index) {
				var that = this
				that.tableDataIndex = index
				that.modaltitle = '提示'
				that.modalcontent = '是否删除第' + (index + 1) + '行'
				that.modalshow = true
				this.$forceUpdate()
			},
			Addsubtable() {
				var that = this;
				var obj = {
					FStorageID: null,
					FStorageName: '',
					MoludName: '',
					MoludID: null,
					StockDeID: 0,
				}
				that.tableData.push(obj)
			},
			modalcancel() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '提醒') {
					// that.PickerShow = true
					this.$refs.popup_workshop.open();
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '提醒') {
					// that.PickerShow = true
					this.$refs.popup_workshop.open();
				} else if (that.modaltitle == '提示') {
					that.tableData.splice(that.tableDataIndex, 1)
				}
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			closeClick() {
				var that = this
				// that.PickerShow = false
				this.$refs.popup_workshop.close();
				that.showModal('提醒', '请选择出入库类型!');
			},
			confirmClick(item) {
				var that = this
				console.log(item);
				// var {
				// 	label,
				// 	id
				// } = item.value[0]
				const formDefaults = {
					FTypeID: item.id,
					FType: item.label
				};
				that.assignFormData(that.baseFormData, formDefaults);
				this.$refs.popup_workshop.close();
			},

			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},

			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},


			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			getValue(payload) {
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				console.log(data);
				const typeHandlers = {
					'人员': () => ({
						StockMan: data.UserName,
						EmplID: data.empolorID
					}),
					'模具': () => ({
						MoludID: data.MoludID,
						MoludName: data.MoludCode
					}),
					'库位': () => ({
						FStorageID: data.FStorageID,
						FStorageName: data.FStorageName
					})
				};
				if (type == '人员') {
					Object.assign(this.baseFormData, typeHandlers[type]());
				} else {
					Object.assign(this.tableData[this.tableDataIndex], typeHandlers[type]());
				}
				console.log(this.baseFormData);
				this.$forceUpdate()
			},
			openBaseScreen(str, index) {
				var that = this;
				var obj;
				if (that.ButtonShow == true) {
					if (str == '人员') {
						obj = {
							cmd: 'getEmplByJobName',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'searchKey', //搜索关键词，应包含在param中
								showText: 'UserName', //查询结果显示的字段
							},
							param: {
								JobName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '模具') {
						that.tableDataIndex = index
						obj = {
							cmd: 'ZS_Droplist_Molud',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'searchKey', //搜索关键词，应包含在param中
								showText: 'MoludCode', //查询结果显示的字段
							},
							param: {
								MoludID: 0,
								FWorkshopID: that.FWorkshopID,
								MoludCode: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '库位') {
						if (that.baseFormData.FStorageName) {
							return
						}
						that.tableDataIndex = index
						obj = {
							cmd: 'MJ_StorageList',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: true, //是否查询
								searchKey: 'FStorageName', //搜索关键词，应包含在param中
								showText: 'FStorageName', //查询结果显示的字段
								arrayList: 'ds1'
							},
							param: {
								FType: that.baseFormData.FTypeID == 'LY' ? 'GH' : 'LY',
								MoludID: that.tableData[that.tableDataIndex].MoludID || 0,
								FStorageID: 0,
								FStorageName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					}
					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}

			},




			submit() {
				var that = this
				var msg
				var show = true
				var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));
				var parentData
				that.tableData.forEach((item, index) => {
					if (!item.FStorageID) {
						msg = '请输入第' + (index + 1) + '行库位'
						show = false
					}
					if (!item.MoludID) {
						msg = '请输入第' + (index + 1) + '行模具'
						show = false
					}
				})
				if (show) {
					var obj = {
						EquipmentID: that.baseFormData.EquipmentID,
						FType: that.baseFormData.FTypeID,
						FStorageID: that.tableData.map(item => item.FStorageID).join(','),
						MoludID: that.tableData.map(item => item.MoludID).join(','),
						StockDeID: that.tableData.map(item => item.StockDeID).join(','),
						StockID: that.baseFormData.StockID,
						StockMan: that.baseFormData.StockMan,
					}
					console.log(obj);
					that.Request.request('SaveMoldStorage', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							parentData = initData[initData.length - 1]
							that.$refs.framework.ToLevel(parentData)
						} else {
							that.showModal('报错', ret.data.ds[0].msg);
						}
					})
				} else {
					that.showModal('报错', msg);
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getMoldStorageDetail', {
						StockID: id
					}, function(ret) {
						that.showMLoading = false
						console.log(ret);
						that.ButtonShow = false
						const [firstItem] = ret.data.ds;
						// that.baseFormData = firstItem
						const formDefaults = {
							StockMan: firstItem.StockMan ?? '',
							BillDate: formatDateTime(firstItem.BillDate),
							FType: firstItem.FType ?? '',
							StockMan: firstItem.StockMan ?? ''
						};
						that.assignFormData(that.baseFormData, formDefaults)
						that.tableData = ret.data.ds1 || [];
					})
				} catch (e) {
					that.showMLoading = false
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},


			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	@font-face {
		font-family: CustomFont;
		src: url('/static/assets/css/moldfont/iconfont.ttf');
	}

	// 查询按钮
	.AddBottomBox {
		width: 100%;
		display: flex;
		align-items: center;
		padding: 2px 5px;
		justify-content: flex-end;
		box-sizing: border-box;

		.CancelBtnIcon {
			.icon {
				padding: 0;
				margin: 0;
			}
		}

		.CancelBtn {
			margin: 0 5px;
			align-items: center;
			text-align: center;
			display: flex;
			justify-content: center;
			background-color: #fff;
			color: #51d0d0;
			border: 1px solid #51d0d0;
			min-height: 45px;
			min-width: 80px;

			border-radius: 4px;
			font-size: 14px;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
			transition: all 0.3s ease;

			&:active {
				background-color: #e6f7f7;
				transform: translateY(1px);
			}
		}
	}













	/* 车间弹窗容器 */
	.popup-container {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
		background-color: rgba(0, 0, 0, .5);
	}

	/* 车间选择区域 */
	.workshop-container {
		flex: 1;
		padding: 16px 16px 0;
		box-sizing: border-box;
		overflow: hidden;
		display: flex;
		align-items: center;
		height: 100%;
		justify-content: space-around;
	}

	.workshop-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 25%;
		height: 100%;
		align-items: center;
		width: 70%;
		margin: 0 auto;
		justify-content: space-around;
	}

	/* 车间选择方块 */
	.workshop-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		text-align: center;
		background: linear-gradient(135deg, #72DFDD, #50CFCE, #3AB4B3);
		border-radius: 12px;
		padding: 25px;
		color: white;
		font-size: 18px;
		font-weight: bold;
		cursor: pointer;
		height: 20vh;
		transition: transform 0.3s ease, box-shadow 0.3s ease;
		box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.1);
	}

	/* 触摸时的缩放效果 */
	.workshop-item:active {
		transform: scale(0.98);
		box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.1);
	}

	.workshop-info {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;

		.uni_icons {
			margin: 0 4% !important;
			padding: 0 !important;
		}
	}

	/* 车间名字 */
	.workshop-name {
		font-size: 30px;
		// margin-bottom: 6px;
		font-weight: bold;
		color: #fff;
		text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
	}

	/* 备注信息 */
	.workshop-remark {
		font-size: 18px;
		color: #ddd;
		margin-top: 6px;
		text-align: center;
		line-height: 1.5;
		font-weight: 500;
		letter-spacing: 0.5px;
	}

	.popup-bottom {
		width: 100vw;
		height: 80px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.close-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 60px;
		height: 60px;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		transition: background 0.2s ease;
	}

	.close-button:active {
		background: rgba(255, 255, 255, 0.4);
	}

	.close-button .uni-icons {
		opacity: .7;
	}
</style>